package OOPAndMultiThreadArchiveManager.Client.Views;

import OOPAndMultiThreadArchiveManager.Client.Models.UserInfo;

import javax.swing.*;

public class MainView {
    private JPanel mainPanel;
    private JMenuBar mainMenu;
    private JMenu UserManage;
    private JMenu ArchiveManage;
    private JMenu UserInfoManage;
    private JFrame frame;
    private UserInfo userInfo;
    private JMenuItem[] userManageItem = new JMenuItem[]{
            new JMenuItem("新增用户"),
            new JMenuItem("修改用户"),
            new JMenuItem("删除用户")
    };
    private JMenuItem[] archiveManageItem = new JMenuItem[]{
            new JMenuItem("下载档案"),
            new JMenuItem("上传档案"),
    };
    private JMenuItem[] userInfoManageItem = new JMenuItem[]{
            new JMenuItem("修改密码"),
    };

    public MainView(UserInfo userInfo) {
        this.userInfo = userInfo;
        frame = new JFrame("MainView");
        addMenuItems(UserManage, userManageItem);
        addMenuItems(ArchiveManage, archiveManageItem);
        addMenuItems(UserInfoManage, userInfoManageItem);
        windowLink();
        accessCheck();
        frame.setContentPane(mainPanel);
        frame.setJMenuBar(mainMenu);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setSize(800, 480);
        frame.setLocationRelativeTo(mainPanel);
        frame.setVisible(true);
    }

    private void addMenuItems(JMenu menu, JMenuItem [] items) {
        for (JMenuItem item : items) {
            menu.add(item);
        }
    }

    private void accessCheck() {
        UserManage.setVisible(userInfo.role.equals("Administrator"));
        ArchiveManage.getItem(0).setVisible(userInfo.role.equals("Administrator") || userInfo.role.equals("Operator"));
    }

    private void windowLink() {
        for (int i = 0; i < 3; i++) {
            int finalI = i;
            UserManage.getItem(i).addActionListener(e -> new UserManageView(userInfo, finalI));
        }
        for (int i = 0; i < 2; i++) {
            int finalI = i;
            ArchiveManage.getItem(i).addActionListener(e -> new ArchiveManageView(userInfo, finalI));
        }
        UserInfoManage.getItem(0).addActionListener(e -> new UserInfoManageView(userInfo));
    }
}
